package team.yidong.fenda.payUtil;

import org.springframework.stereotype.Component;
import team.yidong.fenda.payUtil.ClientCustomSSL;
import team.yidong.fenda.payUtil.PayUtil;
import team.yidong.fenda.payUtil.StringUtil;
import team.yidong.fenda.payUtil.WxPayConfig;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by xuanlong on 2017/12/22.
 */
@Component
public class WxRefund {
    /**
     * 医院提问微信支付退款
     *
     * @param out_trade_no
     * @param total_fee
     * @param refund_fee
     */
    public void wxRefund(String out_trade_no, String total_fee, String refund_fee) {
        // 商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔
        String out_refund_no = UUID.randomUUID().toString().replace("-", "");
        //生成的随机字符串
        String nonce_str = StringUtil.getRandomStringByLength(32);// 随机字符串
        Map<String, String> packageParams = new HashMap<String, String>();
        packageParams.put("appid", WxPayConfig.appid);
        packageParams.put("mch_id", WxPayConfig.mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("out_refund_no", out_refund_no);
        packageParams.put("total_fee", total_fee);
        packageParams.put("refund_fee", refund_fee);
        packageParams.put("op_user_id", WxPayConfig.mch_id);
        String preStr = PayUtil.createLinkString(packageParams);// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口
        String mysign = PayUtil.sign(preStr, WxPayConfig.key, "utf-8").toUpperCase();

        String xml = "<xml>" +
                "<appid>" + WxPayConfig.appid + "</appid>" +
                "<mch_id>" + WxPayConfig.mch_id + "</mch_id>" +
                "<nonce_str>" + nonce_str + "</nonce_str>" +
                "<sign><![CDATA[" + mysign + "]]></sign>" +
                "<out_trade_no>" + out_trade_no + "</out_trade_no>" +
                "<out_refund_no>" + out_refund_no + "</out_refund_no>" +
                "<total_fee>" + total_fee + "</total_fee>" +
                "<refund_fee>" + refund_fee + "</refund_fee>" +
                "<op_user_id>" + WxPayConfig.mch_id + "</op_user_id>" +
                "</xml>";


        String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        try {
            String s = ClientCustomSSL.doRefund(createOrderURL, xml);
            System.out.println("s:" + s);

            //改变支付数据库中的是否退款
            //新增退款数据库数据

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
